<template>
  <el-form :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px" ref="formRef">
    <el-form-item label="事项主题" prop="title">
      <el-input v-model="formData.title" placeholder="请填写事项主题" clearable maxlength="32"/>
    </el-form-item>
    <el-form-item label="事项描述" prop="content">
      <el-input v-model="formData.content" placeholder="请填写事项描述" type="textarea" :rows="3"/>
    </el-form-item>
    <el-form-item label="确认人" prop="executorIds">
      <el-select v-model="formData.executorIds" placeholder="请选择确认人" clearable filterable multiple collapse-tags collapse-tags-tooltip>
        <el-option v-for="item in confirmUsers" :key="item.userId" :label="item.userName" :value="item.userId"/>
      </el-select>
    </el-form-item>
    <el-row justify="end" v-if="!formData.id"> <!-- 日历/事项列表编辑处理 -->
      <el-button size="small" @click="closeForm">取消</el-button>
      <el-button size="small" type="primary" @click="submitData(formRef)">保存</el-button>
    </el-row>
  </el-form>
</template>

<script>
// 其他应收

import Document from '/@/components/document/index.vue'
import {toRefs, ref, reactive, onMounted} from 'vue'
import {formatDate} from '/@/utils/formatTime'
import moneyApi from '/@/api/money'
import Cookies from 'js-cookie'

export default {
  name: 'OtherReceivable',
  emits: ['update:code'],
  props: {
    code: {
      default: null,
      type: String
    }
  },
  components: {
    Document
  },
  setup(props, context) {
    const formRef = ref()
    const state = reactive({
      formData: {
        title: '其他应收',
        type: 'OTHER_RECEIVABLE'
      },
      formRules: {
        title: {required: true, message: '请填写事项主题', trigger: 'blur'},
        executorIds: {required: true, message: '请选择确认人', trigger: 'change'}
      },
      confirmUsers: [],   // 确认人列表
      attachList: [],     // 附件列表
    })

    const initData = () => {
      state.formData = {
        id: null,
        title: '其他应收',
        type: 'OTHER_RECEIVABLE',
        content: '',
        occurDate: null,
        actionStartTime: null,
        actionEndTime: null,
        executorIds: [],
        relateItems: [],
        remark: null,
        attach: '',
        attachNames: '',
        priority: 0,
        remindState: 'NONE',
        remindType: [],
        amount: 0,
        capitalStreamNo: null,    // 钱相关事项特有流水号, 系统自动生成
        capitalTypeId: null,
        capitalAccountId: null,
      }
    }
    const initConfirmUser = () => {
      // 获取确认人列表（钱模块）
      moneyApi.getCapitalUsers('capitalStream').then(res => {
        state.confirmUsers = res.data
        // 获取确认人的历史选择记录
        moneyApi.getConfirmRecord(state.formData.type).then(res => {
          if (res.data) {
            state.formData.executorIds = []
            res.data.forEach(confirmId => {
              for (let i = 0; i < state.confirmUsers.length; i++) {
                let confirmUser = state.confirmUsers[i]
                if (confirmUser.userId == confirmId) {
                  state.formData.executorIds.push(confirmId)
                  break
                }
              }
            })
          } else {  // 没有历史选择记录
            // 如果当前用户为确认人之一, 默认加入
            let selfId = Cookies.get('userId')
            for (let i = 0; i < state.confirmUsers.length; i++) {
              let confirmUser = state.confirmUsers[i]
              if (confirmUser.userId == selfId) {
                state.formData.executorIds = [state.selfId]
                break
              }
            }
          }
        }).catch(e => console.log(e))
      }).catch(e => console.log(e))
    }
    const submitData = (formEl) => {
      formEl.validate(async (valid) => {
        if (!valid) {
          return false
        }
      })
    }
    const closeForm = () => context.emit('update:code', '')

    onMounted(() => {
      initData()
      initConfirmUser()
      // 行动时间默认现在
      let nowTime = formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS')
      state.formData.actionStartTime = state.formData.actionEndTime = nowTime
      state.formData.occurDate = nowTime.substring(0, 10)
    })

    return {
      formRef,
      ...toRefs(state),
      submitData,
      closeForm
    }
  }
}
</script>

<style scoped lang="scss">

</style>
